
// train panel 
CTrainP = function() {
	
};

CTrainP.prototype = {
	
	initialize: function(p) {
		
		var self = this;
		
		// make frame. 
		p.append(this.form = $('<form>', {id: 'train_form' , 'class':'ext_cstl'})
				.append($('<fieldset>')
					.append($('<legend>', {id:'train_f_legend'}).text('Train'))
				)
		);
			
			
		// make field option 
		debug.log(this, 'this', this, ' train form ');
		
		// make tables
		// var sols_table = $('<table>', {id: 'tbl_t_sols', 'class':'t_p_sols_tbl'}) ;
		$('#train_form > fieldset')
			.append( $('<table>', {id: 'tbl_t_sols', 'class':'ext_cstl_tbl'}) );
			
		// add btn for calc  : remains   
		this.form.append( this.calcbtn = $('<button>',{'id': 'calc'}).text('calc'));
		// btn for train start 
		this.form.append( this.trinabtn= $('<button>',{'id': 'train'}).text('start'));
		
		// btn for clear 
		this.form.append( this.clearbtn= $('<button>',{'id': 'clear'}).text('clear'));
		
		
		this.form.submit(function () { return false; }); // so it won't submit

		//  res calc 
		this.form.append( this.calc_res = $('<p>',{'id': 'calc_res'}));

		// add handler 
		this.calcbtn.click(function() {

			// get solnum & check on ly 1 num exists
			var cnt = 0;
			self.input_num =0; 
			self.input_type =0;
			
			// need to exchnage res 
			var moreg = {f:0, w:0, i:0 , total: 0 };
			
			$.each(self.canSols, function (i, cansolT) {
				
				var num =$("#sols_type_row" + cansolT + " > td > :input").val();
				if ( num > 0 )  {
					if (cnt++ > 1) return false;
					self.input_num = parseInt(num); 
					self.input_type = cansolT;
				}
			});
			
			if ( cnt> 1) {
				alert(' only can sel 1 type');
				return;
			}
			
			// calc res  : compare to cstl res 
			var possible = false;
			
			// var cost = calReqRes(self.input_type, self.input_num);
			var aCost  = CDB.SOLS.COST[ self.input_type ];

			var cost = {};
			for (p in aCost ) {
				cost[p] = aCost[p] * self.input_num;
			}
			// remian min food 
			cost.f += CDB.getCurUserInfo().MinFood;
			
			var res  = em.cstlmgr.getCurCstl().res;

			debug.log( this, ' train Need cost: ', cost);
	
			var calc_ret = CUtil.calcNeedRes(res, cost );

			
			// possible �show 
			var result_str = "";
			var result_class ={};
			
			if ( calc_ret.possible) {
				result_str = "possible!!";
				result_class = {'color':'blue'};
			}  else {
				result_str = "IMpossible!!";
				result_class = {'color':'red'};
			}

			self.calc_res.empty().css(result_class)
			.append($('<p>').text( result_str + ' F:' + cost.f + ' W:' + cost.w + ' I:' + cost.i + ' G:' + cost.g ) )
			.append($('<p>').text( 'exchange for : F:' + calc_ret.exchange.f 
												+ ' W:'  + calc_ret.exchange.w
												+ ' I:' + calc_ret.exchange.i)) 
			.append($('<p>').text( ' remained res : G:' + (res.g - cost.g - calc_ret.exchange.total)    ) )	;
					
			// store 
			self.ex_res = calc_ret.exchange;

			res = undefined;
		});			


		this.clearbtn.click(function() {
			if ( !self.canSols) return;
			
			$.each(self.canSols, function (i, cansolT) {
				$("#sols_type_row" + cansolT + " > td > :input").val(0);
			});
		});
		
		
		this.trinabtn.click( function() {
			self.startTrain();	
		});
		
	},
	
	updateContents: function(cstl_idx) {
		var self = this;
		
		function updateSols() {
					// make tables
			var s_name = ['in','s', 'POR', 'x', 'x' ,   	 'x', 'HNT' ,'LAN', 'x' , 'CA' ,
							'Ber', 'x' ,'x', 'x' , 'OV' ,	'x', 'KA' ,'x', 'x' , 'x' ,
			];
			
			$('#tbl_t_sols').empty();
			
			var sols = em.cstlmgr.getCurSols();
			self.canSols = [];
			
			var possible_sols = [CDB.SOLS.SPY, CDB.SOLS.LANU, CDB.SOLS.CARRIER, CDB.SOLS.BER , CDB.SOLS.OVER, CDB.SOLS.KAKL, CDB.SOLS.ASS  ];
			
			// calc max num :: from res.. :  
			var sols_maxs = [];
			var cur_sol_max = 0;
			var cstlinfo = em.cstlmgr.getCurCstl();
			var res  = cstlinfo.res;	
			$.each(sols, function (i, sol) {
				
				if( sol[1] > 0  || possible_sols.indexOf (sol[0]) != -1  ) {
					self.canSols[i] = sol[0];
					
				// cur_sol_max = CUtil.calcMaxSolNum_ExRes( sol[0], res  ); 
					
					$('#tbl_t_sols').append( 
						$('<tr>', {'id': 'sols_type_row' + sol[0] }).append(
								$('<td>').text( s_name[i]))
							.append(
								$('<td>').text( sol[1]))
							.append(
								$('<td>').append($('<input type=text>', {'id': 'input_solnum' + sol[0]})) )	// 2 td
							.append(
								$('<td>').text(  cur_sol_max  ))		// max passible. :  
							.append(
								$('<td>').append( $('<button>)').text('max')))		// set max btn 
	 
					); // table
				}
			} );
		};
		
		// get sols info : always .. 
		var jcb = $.Callbacks();
		
		jcb.add( function (data) {
			debug.log(self, 'sols ', data);
			delete jcb;
			
			if(data.code == 0 && data.ret ) {
				// update solders
				 em.cstlmgr.updateSols(data.ret.soldiers);
				 updateSols();
			} else {
				// alert( 'barra error : barr lv  0 ? ' +data.code);
				debug.log(this, 'barra error : barr lv  0 ? ' +data.code);
			}
			 
		});
		em.tasks.getSols(jcb);
		

	},
	show: function(cstl_idx) {
		// get cstl idx info  .. update 
		this.updateContents(cstl_idx);
		$('#train_form').show();
	},
		
	getValue: function() {
	// this.session_key = $("#id_session_key").val();
	console.log($("#sols_type_row2 > td > :input").val());
	console.log($("#input_solnum2").val());
	console.log($("#sols_type_row" + 2 +":input").val());
	console.log($("#sols_type_row" + 2 +":input").val());
	console.log($("#sols_type_row" + 2 +":input").val());
	this.solnum = $("#sols_type_row" + 2 +":input").val();
	// this.soltype = $('select[name=sol_type]').val();
	// this.cstlindex = $('select[name=cstlindex]').val();
	if ( this.solnum == '') {
		console.log('=========== no valid');
	}
	console.log( this.solnum);
	// var soltype = $('#selid > option:selected').val(); // id 占쏙옙占쏙옙. 
	},
	
	
	startTrain: function() {
		// get cur cstl info. 
		// get form value 
		var self= this;
		if ( !self.input_type  || 
			! self.input_num ) {
				alert (' slect first ');
				return;
			}
			
		function done_cb ( data ) {
			debug.log( self, 'Train result !! ' , data.code	);
 			var res_str = '';
			if ( data.code == 0 ){
				//when ok .  reflect desc res .. 
				var cstlinfo = em.cstlmgr.getCurCstl();
				var res  = cstlinfo.res;	
					
				em.cstlmgr.updateRes({f: res.f - self.ex_res.f, w: res.w - self.ex_res.w , 
									i: res.i - self.ex_res.i , g: res.g - self.ex_res.g});			
				res_str = 'OK';
			} else {
				res_str = '' + data.code;
			}
		
			
			if ( data.code == 2310 ) {
				res_str += 'Already training ';
			}
			alert( "Ret Train :" + res_str);
			return;
		};
		
		em.tasks.trainSol(em.cstlmgr.getCurCstlIdx(), 
					{type : self.input_type , num : self.input_num },
					{g2f: self.ex_res.f,  g2w: self.ex_res.w, g2i: self.ex_res.i} ,
					done_cb
					);
		
		

	},	 
};


/*
	 ============== building panel 
*/



CBuildP = function() {
};


CBuildP.prototype = {
	
	
	initialize: function(p) {
		
		var self = this;

		// make frame. 
		p.append(this.form = $('<form>', {id: 'build_form' , 'class':'ext_cstl'})
				.append($('<fieldset>')
					.append($('<legend>', {id:'train_f_legend'}).text('BUILD'))
				)
		);
			
		// make field option 
		debug.log(this, 'this', this, ' build form  ');
		
		$('#build_form').append(  $('<table>', {id: 'tbl_blds', 'class':'ext_cstl_tbl'}) );
		
		// refresh btn 
		$('#build_form').append( $('<button>', {'id': 'build_recalc'}).text('reCalc'));
		
		this.form.submit(function () { return false; }); // so it won't submit

	
		$('#tbl_blds > #build_recalc').click(function() {
			self.checkPossibleBlds();
		});	
		
		this.checkPossibleBlds();
		
	},
	
	updateContents: function() {
		var self = this;
		var cstl = em.cstlmgr.getCurCstl();
		
		$('#tbl_blds').empty();
		
		// add tables for each blds 
		$.each( CDB.BUILD , function (i, bld) {
				$('#tbl_blds').append( 
					$('<tr>', {'id': 'blds_type_row' + i })
						.append(
							$('<td>').text( bld.name))
						.append(
							$('<td>').text( cstl.city[ bld.pos ]))
							
							// add hidden 
							// <INPUT TYPE="hidden" NAME="objectName" VALUE="hiddenValue">
						.append(
							$('<td>').append($('<input>').attr('type','hidden').val(bld.type)) )
						.append(
							$('<td>').width('50px').append($('<button>').attr('width','30px').text('Up') ))	// 2 td
						)	// tr
 
		} );
		
		// add handler 
		// start  build 
		$('#tbl_blds tr td button').click(function() {

			var bld = $(this).parent().parent();	// tr
			
			var type = bld.find('input').val();
			console.log(bld.find('input').val());
			console.log(bld.find('td').find('input').val());
			console.log(bld.find('input').val());
			console.log(bld.find('input').val());
			
			var lv = parseInt( bld.find('td').eq(1).text() );

			self.startBuild(type, lv);

		});		
	},
	
	show: function() {
		this.updateContents();
		$('#build_form').show();
	},
	// get each row & get lv  & get req res 
	// calc cur res status 
	// set row color 
	checkPossibleBlds:  function() {
		var self= this;
		
		var blds = $('#tbl_blds tr');
		$.each( blds, function (i, bld) {
			//if ( i==0 ) return ; // skip header  : no header
			
			var bld_name = $('#tbl_blds tr').eq(i).find('td').eq(0).text();
			var lv_str = $('#tbl_blds tr').eq(i).find('td').eq(1).text();
			var lv = parseInt(lv_str);
			var type = $('#tbl_blds tr').eq(i).find('td').find('input').val();
			
			// calc res  : compare to cstl res 
			var cstlinfo = em.cstlmgr.getCurCstl();
			var res  = cstlinfo.res;

			debug.log( this, ' cur type', type, 'lv : ', lv);
			var cost = CDB.getBuildRes(type, lv) ;	
			
			debug.log( this, ' cost ', cost);
			
			if ( ! cost) return ;		// no res info : go next 
			
			// remain minimum f : 
			cost.f += CDB.getCurUserInfo().MinFood;

			var calc_ret = CUtil.calcNeedRes(res, cost);
			 
				// return {'possible': possible, 'exchange': moreg };
			if ( calc_ret.possible ) {
				bld.bgColor = 'white';
			} else {
				bld.bgColor = 'black';
			}
		});
	},	 
	
	startBuild: function(type, lv) {
		// get cur cstl info. 
		// get form value 
		// get cur cstl info. 
		// get form value 
		var self= this;
		if ( type === undefined || lv === undefined  ) { 
				alert (' slect type or lv ');
				return;
			}
			

		var dfd = $.Deferred();

		// OK : COLOR -> YELLOW
		// result - > cd list  update to cstlmgr by tasks 
		function processRet(result) {
			debug.log( self, 'this', self, result);
			
		};
		
		// only success
		$.when(dfd).then( function(result) {
						debug.log(self, 'ret BUILD Success!!', result);
						// move cstl to update new res 
						em.cstlmgr.moveCstlAt( em.cstlmgr.getCurCstlIdx() );
						}
						, function(result) {
							var error_str = '';
							if( result.code == 704 ) error_str = 'no slot for bld: need bless of bld'; 
							if( result.code == 708 ) error_str = 'Need more Res.. check !!'; 
							alert('build fail :' + result.code + error_str);
						}
		);

		// calc res  : compare to cstl res 
		var res  = em.cstlmgr.getCurCstl().res;
		// remain minimum f : 
		var cost = CDB.getBuildRes(type, lv) ;	
		cost.f += CDB.getCurUserInfo().MinFood;
		debug.log( this, ' build Need cost: ', cost);

		var calc_ret = CUtil.calcNeedRes(res, cost);

		em.tasks.doBuild( dfd, type, {g2f: calc_ret.exchange.f,  g2w: calc_ret.exchange.w, g2i: calc_ret.exchange.i, total:calc_ret.exchange.total }  );
							
		
	},	 
};



/*
	 ============== studying panel 
*/



CStudyP = function() {
};


CStudyP.prototype = {
	
	
	initialize: function(p) {
		
		var self = this;

		// make frame. 
		p.append(this.form = $('<form>', {id: 'study_form' , 'class':'ext_cstl'})
				.append($('<fieldset>')
					.append($('<legend>', {id:'train_f_legend'}).text('STUDY'))
				)
		);
			
		// make field option 
		debug.log(this, 'this', this, ' study_form form  ');
		
		$('#study_form').append(  $('<table>', {id: 'tbl_studies', 'class':'ext_cstl_tbl'}) );
		
		// refresh btn 
		// $('#study_form').append( $('<button>', {'id': 'build_recalc'}).text('reCalc'));
		
		this.form.submit(function () { return false; }); // so it won't submit
		
		this.checkPossible();
		
	},
	
	updateContents: function() {
		var self = this;
		
		// 
		function updateStuies() {
			//
			var cstl = em.cstlmgr.getCurCstl();
			// studys
			$('#tbl_studies').empty();
			
			// add tables for each blds 
			$.each( CDB.STUDY , function (i, s) {
					if ( ! cstl.studies[s.pos]  )  return false;	// exit each loop 
					
					$('#tbl_studies').append( 
						$('<tr>', {'id': 'studies_type_row' + i })
							.append(
								$('<td>').text( s.name))
							.append(
								$('<td>').text( cstl.studies[ s.pos ][1]))	//lv
							.append(
								$('<td>').text( cstl.studies[ s.pos ][2]))	//possible 
							.append(
								$('<td>').text( ''))	// status 
								
								// add hidden 
							.append($('<input>').attr('type','hidden').val(s.type)) 
							
							.append(
								// $('<td>').width('50px').append($('<button>').attr('width','30px').text('DO') ))	// 2 td
								$('<td>').width('50px').append($('<span>').attr('width','50px')
									.append( $('<p>').text('DO') )) )	// 2 td
							)	// tr
			} );
			
			// add handler 
			$('#tbl_studies tr td span p').click(function() {
	
				var s = $(this).parent().parent().parent();	// tr
				
				var type = s.find('input').val();
				console.log(s.find('input').val());
				var lv = parseInt( s.find('td').eq(1).text() );
	
				self.startStudy(type, lv);
			});		
			return;
		}
		
		var jcb = $.Callbacks();
		
		jcb.add( function (data) {
			var studies = data.ret;
			delete jcb;
				
			 // {"code":0,"ret":[[1,1,1],[2,1,1],[3,0,1]],"ext":[4,4]};
			debug.log(self, 'this', this, 'got studies :', studies);
				
			if(data.code == 0 && data.ret ) {
				// update 
				em.cstlmgr.updateStudies(studies);
				updateStuies();
			} else {
				// alert( 'get Study error : Uni lv  0 ? ' + data.code);
								debug.log(this, 'get Study error : Uni lv  0 ?  ' +data.code);
			}
				
			});
		em.tasks.getStudys(jcb);
	},
	
	show: function() {
		this.updateContents();
		$('#study_form').show();
	},


	checkPossible:  function() {
		// get cd list from each cstl 
		// display studying states 
		var cur_studies = em.cstlmgr.getCdsByType( CDB.CDS.STUDY );

		// filter ing.. one 
		var ing_studies = cur_studies.filter ( function(el) { return el.endtime && (el.endtime.getTime() > $now()); } );
		
		// compare table ' type & chekc ing..  with cstl idx
		$.each (  $('#tbl_studies tr') , function ( i, r ) {
			$.each (ing_studies , function (_, s) {
				// find s target == type  
				if ( s.target == r.find('input').val() ) {
					r.css('background-color', 'black');
					r.find('td').eq(3).text('Ing');
					return false;	// exit  each loop 
				}
			});
			
		});
	/*
		var self= this;
			
			var blds = $('#tbl_studies tr');
			$.each( blds, function (i, bld) {
				//if ( i==0 ) return ; // skip header  : no header
				
				var bld_name = $('#tbl_studies tr').eq(i).find('td').eq(0).text();
				var lv_str = $('#tbl_studies tr').eq(i).find('td').eq(1).text();
				var lv = parseInt(lv_str);
				var type = $('#tbl_studies tr').eq(i).find('td').find('input').val();
				
				// calc res  : compare to cstl res 
				var cstlinfo = em.cstlmgr.getCurCstl();
				var res  = cstlinfo.res;
	
				debug.log( this, ' cur type', type, 'lv : ', lv);
				var cost = CDB.getBuildRes(type, lv) ;	
				
				debug.log( this, ' cost ', cost);
				
				if ( ! cost) return ;		// no res info : go next 
				
				// remain minimum f : 
				cost.f += CDB.getCurUserInfo().MinFood;
	
				var calc_ret = CUtil.calcNeedRes(res, cost);
									   // return {'possible': possible, 'exchange': moreg };
				if ( calc_ret.possible ) {
					bld.bgColor = 'white';
				} else {
					bld.bgColor = 'black';
				}
			});*/
	
	},	 
	
	startStudy: function(type, lv) {
		// get cur cstl info. 
		// get form value 
		// get cur cstl info. 
		// get form value 
		var self= this;
		if ( type === undefined || lv === undefined  ) { 
				alert (' slect type or lv ');
				return;
			}
			
		debug.log(this, 'Study ', type, lv);
		
		// calc res  : compare to cstl res 
		var res  = em.cstlmgr.getCurCstl().res;
		// remain minimum f : 
		var cost = CDB.getStudyRes(type, lv) ;	
		
		for ( p in cost) {
			cost[p] += lv * 1000;
		}
		
		cost.f += CDB.getCurUserInfo().MinFood;
		debug.log( this, ' getStudyRes Need cost: ', cost);

		var calc_ret = CUtil.calcNeedRes(res, cost);

		// check possible 
		if ( ! calc_ret.possible  ) {
	//		alert(' Not Enough Res!!');
			debug.log(this, 'Not Enough RESs... !!!!!!!!!!!!!');
			return;
		}
		
		var dfd = $.Deferred();

		// OK : COLOR -> YELLOW
		// result - > cd list  update to cstlmgr by tasks 
		function processRet(result) {
			if ( result.code == 0 ) {
				debug.log(self, 'ret Sutdy Success!!', result);
				alert( 'Study OK');
			} else {
				var str = '';
				if ( result.code == 1003) str = 'studying at others';
				// if ( result.code == 1003) str = 'studying at others';
				debug.log( self, ' Sutdy Fail... ', result , str );
				alert('Study Fail' + result.code + ' : ' + str);
			}
			// move cstl to update new res 
			em.cstlmgr.moveCstlAt( em.cstlmgr.getCurCstlIdx() );
		};
		
		// only success
		$.when(dfd).then( processRet, processRet );


		em.tasks.doStudy( dfd, type, 
				{g2f: calc_ret.exchange.f,  g2w: calc_ret.exchange.w, g2i: calc_ret.exchange.i, total:calc_ret.exchange.total }  );
							
		
	},	 
};




/*
	 ============== SP30  panel 
*/



CSP30P = function() {
};


CSP30P.prototype = {
	
	objName: 'CSP30Panel:',
	
	initialize: function(p) {

		var self = this;
		debug.log(this, 'this', this, ' init ');
	
		// make frame.
		$('#ctif_0')
			.after( $('<div>', {'id': 'id_sp30_panel', 'class': 'uspvp_panel'}) 
				.append($('<p>').text('sp 30'))
				.append( $('<button>', { id: 'sp30_updae_btn'}).css({'width':'60px;'}).text('Refresh') )
			
			
		);

		// update btn 
		$('#id_sp30_panel #sp30_updae_btn').click( function () {
			// alert('pushed');
			self.show();
		});
		//  make ext panels.  & attach  
 
		var cstls = CDB.getCurUserCtsl();
		var p_style = {'background-color':'white', 'width':'150px', 'height':'250px',
			 'margin': '10px 10px 10px 10px' }; 
		$('#id_sp30_panel').append(  $('<div>').css({'position':'absolute', 
						'top':'0px', 'left': '0px',
						'opacity': '0.5',
						'background': 'url(./images/sp30_back.jpg)'}) );
						
		$('#id_sp30_panel').append(  $('<div>').css({'position':'absolute', 'top':'0px', 'left': '0px'}))
		
			// .append(  $('<div>').css({'position':'absolute', 'top':'0px', 'left': '0px'}) );
			.append( this.t_con = $('<div>').css({'float':'left'}).css(p_style) )
			.append( this.s_con = $('<div>').css({'float':'left'}).css(p_style) )
			.append( this.b_con = $('<div>').css({'float':'left'}).css(p_style) );
		
					// make train panel  & append .
		debug.log( self, 'train');
		if ( self.t_panel == undefined) {
			self.t_panel = new CTrainP(); 
			self.t_panel.initialize(this.t_con);
		}
		self.t_panel.show();
		
		debug.log( self, 'study');
		
		// make train panel  & append .
		if ( self.s_panel == undefined) {
			self.s_panel = new CStudyP(); 
			self.s_panel.initialize(this.s_con);
		}
		self.s_panel.show();
		
		debug.log( self, 'build');
		
		// make train panel  & append .
		if ( self.b_panel == undefined) {
			self.b_panel = new CBuildP(); 
			self.b_panel.initialize(this.b_con);
		}
		self.b_panel.show();					

		self.update_timer = setInterval( function() {
			self.show();
			}, 1210000); 
	},
	

	show: function() {
		var self = this;
		// update contents & show 
		self.t_panel.show();
		self.s_panel.show();
		self.b_panel.show();	
		// this.updateContents();
		// $('#build_form').show();
	},

};




/*
	=====================================================
	-------- US Victoms !!
*/
// EXT panel 
CUsPvpPanel = function() {
	// make main panel  & attach 
	this.initialize();
	this.installHandler();
	
};

CUsPvpPanel.prototype = {
	retLootCB: function(us, result){
		var self = this;
		debug.log(this, ' Got loobt result', result);
		if ( !result ){
			em.util.print_result('Loot Fail!!');
			// self.sel_tr.color('red');
			$('#us_victomtbl tr').eq(us.tblidx+1).css({'background-color': 'black'});		// after header row 
			// $('#us_victomtbl tr').eq(self.sel_tr_idx+1).css({'background-color': 'black'});		// after header row 
			return;
		}
	
	
		em.util.print_result('Loot Success!!' + em.util.print_obj(result));
		// self.sel_tr.color('yellow');
		// $('#us_victomtbl tr').eq(self.sel_tr_idx+1).css({'background-color': 'yellow'});
		$('#us_victomtbl tr').eq(us.tblidx+1).css({'background-color': 'yellow'});
		
	},
	
	makeUsTable:function(){
		this.maketableContents(this.us_con);
	},
	// make us table.. :  
	maketableContents: function(c){
		var self  = this;
		var UsArr = em.worldDA.getUsArr();
		
		// filter : avail us  < 20min 
		this.UsArr = UsArr.filter( function(el){
			if ( el.nextdate.getTime() > $.now() + 10  &&
			     el.nextdate.getTime() < $.now() + 1000 *60 * 20 
			) return true;
		});
		
		debug.log(this, 'this', this, ' makeUsTable ');
		
		// remove prev options
		$('#us_victomtbl').detach();
		var us_table;
		c.append(us_table = $('<table>', {id: 'us_victomtbl', 'class':'us_victomtbl_type'})
						.css({'background-color': '#3Fd3a0', 'font-size': '11px'}) 
						);
		
		us_table.append( 
			$('<tr>', {'id': 'us_vic_row_head' })
				.css({'font-size': '14px' , 'background-color': '#881100'})
				.append(
					$('<td>').text( 'name'))
				.append( $('<td>').text( 'x'))
				.append( $('<td>').text( 'y'))
				.append( $('<td>').text( 'lv'))
				.append( $('<td>').text( 'dur'))
				.append( $('<td>').text( 'time'))
				.append( $('<td>').text( 'over'))
				.append( $('<td>').text( 'lanu'))
				.append( $('<td>').text( 'kakl'))
		); // head row 
				
		$.each(this.UsArr, function (i, us) {
				var tr;
				us_table.append( 
					tr = $('<tr>', {'id': 'us_vic_row' + i })
						.append( $('<td>').text( us.name))
						.append( $('<td>').text( us.x))
						.append( $('<td>').text( us.y))
						.append( $('<td>').text( us.lv))
						.append( $('<td>').text( us.dur))
						.append( $('<td>').text( CUtil.TimeToString (us.nextdate)))
						.append(
							$('<td>', {'class':'att_overNum'}).append($('<input type=text>', {'id': 'in_overNum' + i ,  'width':'30px' })) )	
						.append(
							$('<td>',{ 'class':'att_lanuNum'}).append($('<input type=text>', {'id': 'in_lanuNum' + i,  'width':'30px'})) )	
						.append(
							$('<td>',{'class':'att_kaklNum'}).append($('<input type=text>', {'id': 'in_kaklNum' + i ,   'width':'30px'})) )	
 
				); // table
				 
				// check big bob 
				if( us.dur < 6 ) {
					tr.css({'color':'red' ,'font-weight':'bold'});
				}
				
				// set us data 
				$.data(tr, 'us_data', us);
		} );
		

		// $('#id_train:first-child').before(cstl_option);
		// c.append(us_table);
		
		$('#us_victomtbl tr').click( function () {
			
			debug.log(this, 'click ed.. ', $(this));
			// store sel tr  data 
				// 이게 안되 네... 
			self.sel_us_test = $.data(this,'us_data');
			var regex = /(\d+$)/;
			var id  = $(this)[0].id;
			var index = parseInt(regex.exec(id)[0] ) ;			
			self.sel_us = self.UsArr[index];
			self.sel_us.tblidx = index;
				
			debug.log(this, '=== cur us  ', self.sel_us);

			self.sel_tr_idx = index;
			$(this).css({'background-color': '#4498a4'});
		});
	},
	
	
	initialize: function() {
		var self = this;
		debug.log(this, 'this', this, ' init ');
		// make frame.
		this.us_con = $('<div>', {'id': 'id_uspvp_panel', 'class': 'uspvp_panel'});
		
		// cstl name 
		this.us_con.append($('<p>').text('Good Luck!'));
			
		// add loot btn 
		var lootbtn = $('<button>', { id: 'loot_btn',  'top': '0px;'})
						.css({'width':'60px;'}).text('loo');
		
		lootbtn.click( function(){
				// get cur sel row & go loot 
				var us = self.sel_us;
				
				// get over num
				// var num =$("#us_victomtbl > tr#us_vic_row" + self.sel_tr_idx + "  > td > :input").val();
				// var onum = $('#us_victomtbl tr').eq(self.sel_tr_idx+1).find('td::input:first').val();
				// var lnum = $('#us_victomtbl tr').eq(self.sel_tr_idx+1).find('td:last :input').val();
				
				
				var onum = $('#us_victomtbl tr').eq(self.sel_tr_idx+1).find('.att_overNum :input').val();
				var lnum = $('#us_victomtbl tr').eq(self.sel_tr_idx+1).find('.att_lanuNum :input').val();
				var knum = $('#us_victomtbl tr').eq(self.sel_tr_idx+1).find('.att_kaklNum :input').val();
				// var lnum = $('#us_victomtbl tr').eq(self.sel_tr_idx+1).find('.att_lanuNum :input').eq(1).val();
				debug.log(this, ' get Over num' , onum, 'lanu num:', lnum , ' Kalk : ', knum);
				
				if ( onum > 0 )  {
					us.onum = parseInt(onum); 
				} else { us.onum = 0;}
				
				if ( lnum > 0 )  {
					us.lnum = parseInt(lnum); 
				} else { us.lnum = 0;}
				
				if ( knum > 0 )  {
					us.knum = parseInt(knum); 
				} else { us.knum = 0;}
				
				// make result cb 
				if (! self.lootret_cb ) {
					self.lootret_cb =  $.Callbacks();
					self.lootret_cb.add( self.retcb= function(us, result) { self.retLootCB.apply(self, [us,result]);} );
				}				
				// add job 
				em.jobmonitor.addJob( {name: 'LootUsPvp', fn: em.jobmonitor.lootUs_PVP, param: [us ,self.lootret_cb] });
				// do right now
				em.jobmonitor.doMonitor();
					

				
		});
		
		this.us_con.append(lootbtn);
			
		
				// add AuTO loot btn 
		var autolootbtn = $('<button>', { id: 'autoloot_btn',  'top': '0px;'}).text('auto');
		autolootbtn.click( function(){
				// get cur sel row & go loot 
				var us = self.sel_us;
				// add job 
				em.jobmonitor.addJob( {name: 'AutoLootUsPvp', fn: em.jobmonitor.autoLootUsPvp, param: [] });
				// do right now
				em.jobmonitor.doMonitor();
					
				// make result cb 
				if (! self.lootret_cb ) {
					self.lootret_cb =  $.Callbacks();
					self.lootret_cb.add( self.retcb= function(result) { self.retLootCB(result);} );
				}
		});
		
		this.us_con.append(autolootbtn);
		
		
		this.us_con.insertAfter($('#ctif_0'));		
		outer = this;
		function showCurTime() {
			var d = new Date();
			var time_txt = d.getFullYear() + '-' + (d.getMonth() + 1)  + '-' + d.getDate() 
				 + '  ' + d.getHours() + ':' + d.getMinutes() +':' + d.getSeconds();
			$('#uspvp_clock').detach();
			$('<div>',{'id': 'uspvp_clock'}).html(time_txt).insertBefore('#us_victomtbl');
			// $('#uspvp_clock').insertBefore();
			// outer.us_con.append($('<div>',{'id': 'uspvp_clock'}).html(time_txt) );	
		}
		setInterval ( showCurTime , 1000);
	},
	
	hide: function() {
		$('#id_uspvp_panel').hide();
		
	},
	
	installHandler: function() {
				// set class
		var self = this;
	},
	
	
};















// EXT panel 
CExtCstl = function() {
	
};

CExtCstl.prototype = {
	
	initialize: function(p) {
		var self = this;
		debug.log(this, 'this', this, ' init ');
		
		// make main panel.
		p.append( this.panel = $('<div>', {'id': 'userselectcstl', 'class': 'cstl_usr_sel'}).hide() );

		this.panel.fadeIn(500).fadeTo("slow",0.8);

		// var cstlinfo = em.cstlmgr.getCurCstl();
		// var cstlidx =  em.cstlmgr.getCurCstlIdx();
		
		// cstl name 
		this.panel.append($('<p>', {'id':'ext_cstl_name'}).text( ' nth  Cstl :'));
			
		// add ext btn 
		this.panel.append ($('<button>', { id: 'exit_usercstl',  
									'top': '0px;', 'width': '80px;', 'right':'30px;'}).text('exit')
							.click( function(){
									em.jobmonitor.endUserOperation();
									self.hide();
								})  );
/*
		exitbtn.click( function(){
				em.jobmonitor.endUserOperation();
				self.hide();
		});*/

		
		// this.panel.append(exitbtn);
			
		// add ext control panel 
		
		// show ext panel  with cstl info  . sol train UI
		

		// res state
		// add exchange btn & panel
		this.panel
			.append( $('<div>', {id:'cstl_res_div'}) 
				.append( $('<p>'))		// res state
				.append( $('<button>').text('Exchange'))	// 
				.append( $('<button>').text('- Do -'))	// 
				.append( $('<div>' , {'id': 'ext_res_exchange'})
					.append( $('<ul></ul>')
						.append( $('<li)</li>')
							.append( $('<span>',{'class': 'ext_cstl_res_span'}).text('g2w :'))
							.append( $('<input type=text>')) 
						)
						.append( $('<br/>'))
						.append( $('<li)</li>')
							.append( $('<span>', {'class': 'ext_cstl_res_span'}).text('g2f :'))
							.append( $('<input type=text>')) 
						)
						.append( $('<br/>'))
						.append( $('<li)</li>')
							.append( $('<span>', {'class': 'ext_cstl_res_span'}).text('g2i :'))
							.append( $('<input type=text>')) 
						)
						.append( $('<br/>'))
					)
				) 
			); 		
		// var res_c = $('<div>', {id:'cstl_res_div', 'class':'ext_cstl'});
		// res_c.append ( $('<p>'));
		
		// em.cstlview.updateCstlRes( $('#cstl_res_div p:first'), cstlinfo.res);
		
		// hide exchnage inputs
		$('#cstl_res_div #ext_res_exchange').hide();
		
		// install evt handler 
		$('#cstl_res_div button:first').click( function() {
			$('#cstl_res_div #ext_res_exchange').fadeIn('slow');
		});
		
		$('#cstl_res_div button:last').click( function() {
			$('#cstl_res_div #ext_res_exchange').fadeOut('slow');
				
				// get value 
				console.log( $('#cstl_res_div > ext_res_exchange > ul > li :input').val() );
				console.log( $('#cstl_res_div > ext_res_exchange > ul > li:input').val() );
				console.log( $('#cstl_res_div > ext_res_exchange > ul > li :input') );
				
				console.log( $('#ext_res_exchange > ul  > li :input').val() );
				console.log( $('#ext_res_exchange > ul  > li:input').val() );
				console.log( $('#ext_res_exchange > ul  > li :input') );
				
				console.log( $('#ext_res_exchange > li :input').val() );
				console.log( $('#ext_res_exchange > li:input').val() );
				console.log( $('#ext_res_exchange > li:input'));
				
				console.log( $('#ext_res_exchange :input').val() ); // ok
				console.log( $('#ext_res_exchange :input') );

				console.log( $('#ext_res_exchange ul li').eq(0).find('input').val() );
				console.log( $('#ext_res_exchange ul li').eq(0).find('input'));
				console.log( $('#ext_res_exchange > ul > li :input').eq(0).val() );
				console.log( $('#ext_res_exchange > ul > li').eq(0).find('input'));
				console.log( $('#ext_res_exchange > ul > li:input').eq(0) );
				
				
				var g2w = $('#ext_res_exchange :input').eq(0).val();
				var g2f = $('#ext_res_exchange :input').eq(1).val();
				var g2i = $('#ext_res_exchange :input').eq(2).val();
				
				debug.log(this,  'gogo  exchange food !!' , g2w, g2f, g2i) ;
				
				var self = this;
				em.tasks.exchangeRes( g2f, g2w, g2i,
						// done cb 
					 function() {	 
							debug.log(self, " EXchange food :: success CB is called !!! ") ;
								
							// get cit info : update res 
							em.tasks.getCitInfo( em.cstlmgr.curCstlID(),
								// done cb 
								function(data) {
								});							
						} 
				);
		});
		
		// $('#cstl_res_div').detach();
		// res_c.appendTo(this.panel);
		
		 
		
		
		// show sols info 
		this.panel.append( $('<div>', {id:'selcstl_sols', 'class':'ext_cstl_sols'}) );
/*
		em.cstlview.updateSols(sols_c, cstlinfo.getSols());
	 	$('#selcstl_sols').detach();
		sols_c.appendTo(this.panel);	*/
		
		
			
		
		
		// make nav for train, study, build
		// var ext_nav = $('<nav>')
		this.panel.append ( $('<nav>')
			.append($('<div>' , {'id':'ext_p_nav'}).css('background-color', '#f0f0f0')
				.append( $('<span>').css('width','30px')
					.append($('<a>', {'id': 'ext_p_train', 'class': 'ext_nav_menu','href': '#train'}).text('train')) )
				.append( $('<span>')	
		 			.append($('<a>', {'id': 'ext_p_study', 'class': 'ext_nav_menu', 'href': '#study'}).text('study')) )
				.append( $('<span>')
		 			.append($('<a>', {'id': 'ext_p_build', 'class': 'ext_nav_menu', 'href': '#build'}).text('build')) )
			) );
	
	 	// $('#ext_p_nav').detach();
		// ext_nav.appendTo(this.panel);	
		
		
				// form  div 
		this.panel.append ( $('<div>', {id:'action_form_con', 'class':'ext_cstl_form_con'}) );
		// var action_form_con = $('<div>', {id:'action_form_con', 'class':'ext_cstl'});
	 	// $('#action_form_con').detach();
		// action_form_con.appendTo(this.panel);
		
		
		// // make cstls smmall
		// $('.castleinfo').removeClass('castlefocus');
		// $('.castleinfo').addClass('castle_small');
		
		this.panel.insertBefore($('#ctif_0'));
		
		// this.show();			
	},
	
	// update new selected cstl info  : only content 
	updateContents: function(cstl_idx) {

		var cstlinfo = em.cstlmgr.getCurCstl();
		var cstlidx =  em.cstlmgr.getCurCstlIdx();
		console.log (cstlinfo);
				
		// cstl name 
		$('#userselectcstl #ext_cstl_name').text( cstlidx + ' : ' + cstlinfo.name[1] );
		// this.panel.append($('<p>').text( cstlidx + ' : ' + cstlinfo.name[1]));
			
		em.cstlview.updateCstlRes( $('#cstl_res_div p:first'), cstlinfo.res);
		
		// show sols info 
		em.cstlview.updateSols($('#selcstl_sols'), cstlinfo.getSols());
			
	},
	
	hide: function() {
		$('#userselectcstl').hide();
		
		// make cstls resotre
		$('.castleinfo').removeClass('castle_small');
		$('.castleinfo').addClass('castlefocus');
	},
	show: function(cstl_idx) {
		// update cur cstl status 
		this.updateContents(cstl_idx);
		
		if ( this.cur_panel ) {
			// update cur panel 
			this.cur_panel.updateContents();
		}
		$('#userselectcstl').show();
		
		// make cstls smmall
		$('.castleinfo').removeClass('castlefocus');
		$('.castleinfo').addClass('castle_small');
	},	
	installHandler: function() {
				// set class
		var self = this;
		$('.ext_nav_menu')
			.click(function() {
				debug.log( self, ' clieck3d !!!  menu ext');
				
				// remove form 
				$('.ext_cstl').hide();
				
				var href = $(this).attr('href');	/// get cur href 
				var con = $('#action_form_con');
				switch( href ){
					case '#train':
					debug.log( self, 'train');
					
					// make train panel  & append .
					if ( self.t_panel == undefined) {
						self.t_panel = new CTrainP(); 
						self.t_panel.initialize(con);
					}
					self.t_panel.show();
					self.cur_panel = self.t_panel;
					break;
					
					case '#study':
					debug.log( self, 'study');
					
					// make train panel  & append .
					if ( self.s_panel == undefined) {
						self.s_panel = new CStudyP(); 
						self.s_panel.initialize(con);
					}
					self.s_panel.show();
					self.cur_panel = self.s_panel;
					break;
					
					case '#build':
					debug.log( self, 'build');
					
					// make train panel  & append .
					if ( self.b_panel == undefined) {
						self.b_panel = new CBuildP(); 
						self.b_panel.initialize(con);
					}
					self.b_panel.show();					
					self.cur_panel = self.b_panel;
					break;
				}
			});
		

		$('#ext_p_nav a')
			.click(function() {
				var href = $(this).attr('href');
					debug.log( this, ' --- 222',href);
			});
		$('#ext_p_nav > a')
			.click(function() {
				var href = $(this).attr('href');
					debug.log( this, ' ---333 ',href);
			});
			  
	},
	
	
};




CCstlView = function () {
	this.objName = 'CCstlView';
	var self = this;
	// register event cbs   : fired after system task  : should be after userinfo 
	em.cbs.userchanged.add (function(sols) { self.makeCstls(); });
	
		// clear 
	em.cbs.startuserchange.add (function() { self.clearAll(); });
	
	
	// first cstl move after login ..  
	// if sp30 . make sp30 panel 
	em.cbs.cstlmove1done.add( self.cb_1st_cstlmove = function(cstl_idx){
		
						em.cbs.cstlmove1done.remove( self.cb_1st_cstlmove);
						
						// after login. first update cd. 
						if ( ! self.firstInit ) {
							self.makeSP30Panel();
							self.firstInit = true;
						}
			 	}  );

			
			
};

//  set cstl status : f, g , name  
// updsate att info  : last reason coe for move next cstl 
// reset each casl 
// focus ucr cstl 
// click cur setl : expand catl  with some function button (  addinailtal actions like camp, resarch ,, etc. )

CCstlView.prototype = {

		// init ... 
		initialize: function() {
			var self = this;
			debug.log(this, ' cstl view init');
			
			setInterval ( function() { self.timerFn(); }, 1000);

		}	,
		
		// init ... 
		makeCstls: function() {
			var self = this;

			/// make cstl  UI  per each ctsl
			var cstls = CDB.getCurUserCtsl();
			
			if ( cstls === undefined) {
				debug.log(this, ' No cstl infos!!!');
				return;
			}
			 

			// clear prev cstls . 
			$('.castles_container').empty();
			
			$.each( cstls , function(i, cstl) {
				var cstlWidget = self.factoryCstl(i, cstl);
				// add to <div class='castles_container'>
				$('.castles_container').append(cstlWidget);
				
			} );
			
			// UI   event handler
			
			
			// add move cstl cb 
			var jcb = $.Callbacks('unique');
			

			
			// click handler : 
			// when no job is doing , move that cstl 
			// stop auto next check !! 
			// < - restart method ??  : btn click ? or timeout ??  
			// UI larger  
			$('.castleinfo').click( function() {
				//get index of cstl 
					debug.log(this, 'this', this, $(this)[0].id	);
					debug.log(this, 'this', this, $('.castleinfo:selected')	);
				//  not work debug.log(this, 'this', this, $('.castleinfo:focused')	);
				var regex = /(\d+$)/;
				var id  = $(this)[0].id;
				console.log( id);
				console.log( 'match', id.match(regex) , '$1');
				console.log( 'search',id.search(regex));
				console.log( 'replace' , id.replace(regex, '--$1=='));
				console.log( 'test',regex.test(id	) , '$1');
				console.log( 'exec',regex.exec(id	));
				
				
				var index = parseInt(regex.exec(id)[0] ) ;
				console.log( index);
				
				// clear prev user operationflag 
				em.jobmonitor.endUserOperation();
				
				// check job is doing 
				if ( em.jobmonitor.IsDoing() ) {
					alert( 'job is doing .. wait');
					return;
				}
				
				
				// register done cb for cstl move
				function cstlMoveDone(cstl_idx) {
					em.cbs.cstlmove1done.remove( self.cb_cstlmove);
					// block next job intrude. 
					em.jobmonitor.starUserOperation();
					
					// ui class change.  larger . 
					self.setCurCstl(cstl_idx); 
					
					// init make ext cstl
					if(self.extcstl == undefined) {
						self.extcstl = new CExtCstl();
						self.extcstl.initialize($('#id_frame'));
						// XXX ::  shoud install handler at the different function with making function !!!!!!
						self.extcstl.installHandler();
					}	
					
					// show with cur cstl info 	
					self.extcstl.show(cstl_idx);
				
				} 
				
/*
				jcb.add( cstlMoveDone );
				// move cstl & get info 
				em.tasks.userSelCstl(index , jcb);
				*/

				em.cbs.cstlmove1done.add( self.cb_cstlmove = function(cstl_idx){ cstlMoveDone(cstl_idx);}  );
				em.cstlmgr.moveCstlAt(index);
						
			});
			

			
			
		}	,
		
		
					/*
				SP 30 panel 
			*/
			
		makeSP30Panel: function() {
			// make SP 30 panel when sp30 mode 
			if ( CDB.getCurUserOptions().sp30 && self.sp30_panel == undefined) {
				debug.log( this, 'Make SP 30 Panel...	');
				
				self.sp30_panel = new CSP30P(); 
				self.sp30_panel.initialize();
				self.sp30_panel.show();
			}
		},
		
		
		updateCstlRes: function(con, res){
			var f=0, w=0, i=0, g=0;
			if ( res  ) {
					f = res.f || 0;
					w = res.w || 0;
					i = res.i || 0;
					g = res.g || 0;
			}
			
			con.empty()
				.html( ' F: ' + CUtil.commify(f) + ' w: ' + CUtil.commify(w) + ' :' 
					 + ' I: ' + CUtil.commify(i) + ' G: ' + CUtil.commify(g) );
		},
		
		/*
{"id":843558,"cdtype":1,"target":9,"owner":0,"secs":17539},    //  uni  
{"id":846316,"cdtype":1,"target":10,"owner":0,"secs":69911},	// arena 
{"id":847570,"cdtype":1,"target":13,"owner":0,"secs":26386},   	// fuci
{"id":220951,"cdtype":2,"target":7,"owner":87575,"secs":75168}, //   study  2 ex Arm  7  h id 
{"id":192011,"cdtype":3,"target":15,"owner":152,"secs":4111}    // train  o   3   gid  
		*/
		
		updateCDs: function(index, cds){

			// clear prev Detail list
			this.clearCstlDetail(index);
			
			// var cd_con  = $("#ctif_" + index + " > header > ctif_h_cds" + index  ) ;
			var cd_con  = $("#ctif_h_cds" + index  ) ;
			 // ctif_h_res0
			// sel container
				
						
			this.showCDs(cd_con, cds);
			
			// // attach 
			// $("#ctif_" + index + " > header > ctif_h_cds" + index  )
				// .append(this.cd_con);
			
		},
		showCDs: function(con, cds){
			con.empty();
			$.each ( cds, function(_,cd) {
				var jobname = CDB.CDS.getTypeName( cd.cdtype);
				var target =  CDB.CDS.getTargetName( cd.cdtype, cd.target);
				var str = jobname + "::"+ target + ' : ';
				if ( cd.done) {
					if ( cd.cdtype == CDB.CDS.ATT) 
						return; 	// skip .. expired att 
						
					str += ' Done!';
				} else {
					// str += Math.floor(cd.secs/3600) + ':' +  Math.floor(cd.secs/60) % 60  + ':' + cd.secs % 60;
					str += CUtil.SecToString(cd.secs);
					
					if ( cd.secs < 0 ) str += ' Done' ;
				}
				
				con.append( $('<p>').text( str) );
			});
		},
		
		updateSols: function(con, sols){
			var snum = em.cstlmgr.getSolnum(CDB.SOLS.SPY);			
			var lnum = em.cstlmgr.getSolnum(CDB.SOLS.LANU);			
			var bnum = em.cstlmgr.getSolnum(CDB.SOLS.BER);			
			var onum = em.cstlmgr.getSolnum(CDB.SOLS.OVER);			
			var knum = em.cstlmgr.getSolnum(CDB.SOLS.KAKL);			

			con.empty()
				.html( ' s: ' + snum + ',  lanu: ' + lnum 
					 + ' Ber: ' + bnum + ' Ov: ' + onum + ' K:' + knum );
		},
		
		
		showStudies: function(idx, studies) {
			// nothign todo..  yet...
		},
		
		// f, g , name : 
		setCstlState: function(index, cstlinfo) {
			
			var res = $('<p>');
			this.updateCstlRes(res, cstlinfo.res);
			
			// $("#ctif_" + index  + " > header > ctif_h_res" + index  ).empty()
			$("#ctif_h_res" + index  ).empty()
				.append(cstlinfo.name[1])
				.append(res);
				
			// update ext panel res 
			if ( this.extcstl )	 {
				var ext_res_c = $('#cstl_res_div');
				em.cstlview.updateCstlRes(ext_res_c, cstlinfo.res);
			}
	
		},

		// after get userinfo  update city  : name, xy  
		setCityInfo: function(index, city) {
			
			$("#ctif_h_res" + index  ).empty()
				.append(city.name);
	
		},
		
		

		// att info  
		pushAttInfo: function(index, attinfo) {
			var infostr  = attinfo.h.gid 
				+ (( attinfo.trs.o > 0) ?   ' , o:' + attinfo.trs.o : '' ) 
				+ (( attinfo.trs.b > 0) ?   ' , b:' + attinfo.trs.b : '' ) 
				+ ' sec:' + attinfo.secs 
				+ ' end:'+ attinfo.endtime.getHours() + ':' + 
						attinfo.endtime.getMinutes() + ':' + 
						attinfo.endtime.getSeconds() ;
				
			 $("#id_ct_deta_" + index).append(infostr + '<br/>');
			 // $("#id_ct_deta_" + (index + 1)).append( infostr);
		},
		
		// clear index castl : before start 
		clearCstlDetail: function(index) {
				$("#id_ct_deta_" + index).empty();			 
		},
		
		// focus cur cstl
		setCurCstl: function(index) {
			//clear
			$('.castleinfo').removeClass('castlefocus');
			$("#ctif_" + (index)).addClass('castlefocus');
		},
	
			//   
		updateHDrin: function(index, result) {
			//	{"gold":24148,"price":5135,"refresh":3600,"hero":{"gid":117,"p":11,"i":21,"c1":15,"g":2,"c2":295},"rumor":0}
			// $("#ct_hdrin_" + (index + 1)).html($('<p>').text(infostr));
			//	{"gold":24148,"price":5135,"refresh":3600,"hero":{"gid":117,"p":11,"i":21,"c1":15,"g":2,"c2":295},"rumor":0}
			
			// {"code":0,"ret":{"price":372,"type":2,"refresh":2274}})
			debug.log(this, 3, ' cstlview : got ', result);

			
			// store result
			this.ret_hdrin = this.ret_hdrin || [] ;
			this.ret_hdrin[index] = this.ret_hdrin[index] || {};
			this.ret_hdrin[index] = result;
			this.showHDrin(index, result);
		},
		
		showHDrin: function(index, result){
			var infostr = '';
			if ( result.code == 1304) { 	// no hero info in ret 
				infostr = ' No Space For Hero! ' + result.code;
			} else {
				infostr  = 'Rumor :' + (result.ret.rumor ? 'Got': 'No')  + ' refresh :' + result.ret.refresh 
				+  (result.ret.hero ? ' H gid:' + parseInt(result.ret.hero.gid) : '');
			}

			if ( result.ret.refresh < 0 ) {
				$("#ct_hdrin_" + index).html($('<span>').attr('background-color', 'black'));
			}
			// console.log(infostr);
			$("#ct_hdrin_" + index).html($('<span>').text(infostr));
			
		},

		// click cstl for extend cmd 
		expandCstl: function() {
			
		},
		
/*
		setCurUserCstl: function(cstls) {
			this.usrCstl = cstls;
		},
*/
		
// 	{"id":3070,"name":"\ucc9c\uc0c1\uc131","landtype":3,"x":185,"y":53},
/*
		updateFirstCity: function(index, city) {
			$("#ctif_" + index  + " > header > ctif_h_res" + index  ).empty()
				.append(city.name);
		},	*/

		
		/*
			make Wigets for cstl view 
		*/
		
		factoryCstl: function(i, cstl) {
			// make ... 
/*
		<div class='castles_container'>
		<section class='castleinfo' id='ctif_1'>
			<header>
				C::
			</header>
			<div class='ct_detail' id='id_ct_deta_1'>
				
			</div>
			<footer>
				<div class='ct_hdrin' id='ct_hdrin_1'>
			</footer>
		</section>

*/
			var cstl_section = $('<section>', {id : 'ctif_' + i , 'class': 'castleinfo'});
			cstl_section.append($('<header>')
								.append($('<div>', {'id': 'ctif_h_res' +i }))
								.append($('<div>', {'id': 'ctif_h_cds' +i }))
								
								)
							.append($('<div>', {'id': 'id_ct_deta_' + i}))
							.append($('<footer>')
								.append($('<div>', {'id':'ct_hdrin_'+i, 'class': 'ct_hdrin'}))
							);	// footer
			return cstl_section;
		},


			
		clearAll: function() {
				$('.castles_container').empty();			
		},
		
		/*
			Timer   : only desc time info locally  
		*/
		
		timerFn: function () {
			// update hdrin refresh time
			var self = this;
			if ( this.ret_hdrin) {
				$.each( self.ret_hdrin , function(i, hdrin) {
					if ( ! hdrin ) return ; // go next when empty  
					hdrin.ret.refresh--;
					self.showHDrin(i, hdrin);
				});
			}
		} , 

		
		/*
			 additional panel 
		*/
		
		showUsPanel: function() {
			this.uspv_panel  = this.uspv_panel || new CUsPvpPanel();
			this.uspv_panel.makeUsTable();
		},
};

